package org.openclinic.controller;

import javax.servlet.http.HttpServletRequest;

import org.joda.time.LocalTime;
import org.openclinic.domain.Clinic;
import org.openclinic.domain.HealthProfessional;
import org.openclinic.domain.User;
import org.openclinic.exception.AbstractExceptionHandler;
import org.openclinic.service.AppointmentService;
import org.openclinic.service.MedicalSpecialtyService;
import org.openclinic.service.ReminderService;
import org.openclinic.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class DashboardController extends AbstractExceptionHandler {

	@Autowired
	private AppointmentService appointmentService;
	
	@Autowired
	private Clinic clinic;
	
	@Autowired
	private MedicalSpecialtyService medicalSpecialtyService;
	
	@Autowired
	private ReminderService reminderService;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value = "/dashboard.do", method = RequestMethod.GET)
	public ModelAndView init() {
		LocalTime endTime = new LocalTime(clinic.getAfternoonEndTime());
		ModelAndView mav = new ModelAndView("dashboard.view");
		mav.addObject("startHour", new LocalTime(clinic.getMorningStartTime()).getHourOfDay());
		mav.addObject("endHour", endTime.getMinuteOfHour() == 0 ? endTime.getHourOfDay() - 1 : endTime.getHourOfDay());
		mav.addObject("celebratingBirthday", userService.findCelebratingBirthday());
		mav.addObject("importantReminders", reminderService.findTodayImportantReminders());
		mav.addObject("specialtyList", medicalSpecialtyService.findAvailable());
		
		return mav;
	}
	
	@RequestMapping(value = "/mobile", method = RequestMethod.GET)
	public ModelAndView initMobile(HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("mobile.jsp");
		User user = (User) request.getSession().getAttribute("currentUser"); 
		if (user != null) {
			try {
				mav.addObject("appointmentList", appointmentService.findProfessionalTodayAppointments(((HealthProfessional)user).getUserId()));
			} catch (ClassCastException e) {
				mav.addObject("errorMessage", "Perfil sem acesso.");
				request.getSession().invalidate();
			}
		}
		
		return mav;
	}
	
}
